package flc.ast.activity;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentTransaction;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.imgedit.model.FuncBean;
import com.stark.imgedit.view.CropImageView;
import com.stark.imgedit.view.RotateImageView;
import com.stark.imgedit.view.imagezoom.ImageViewTouch;
import com.stark.imgedit.view.imagezoom.ImageViewTouchBase;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import flc.ast.BaseAc;
import flc.ast.BaseEditFragment;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityPicEditBinding;
import flc.ast.fragment.BeautyFragment;
import flc.ast.fragment.ColorTuneFragment;
import flc.ast.fragment.CropFragment;
import flc.ast.fragment.FilterFragment;
import flc.ast.fragment.RotateFragment;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.apis.ApiManager;
import stark.common.base.IReqRetCallback;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.UriUtil;
import stark.common.basic.view.container.StkLinearLayout;

public class PicEditActivity extends BaseAc<ActivityPicEditBinding> {

    public static final int MODE_NONE = 0;
    public static final int MODE_BEAUTY = 7;// 美颜模式
    public static final int MODE_FILTER = 2;// 滤镜模式
    public static final int MODE_CROP = 3;// 剪裁模式
    public static final int MODE_ROTATE = 4;// 旋转模式
    public static final int MODE_COLOR_TUNE = 8;//色调模式

    public static String sImgPath;
    private Bitmap mRetBitmap;
    private List<FuncBean> mFuncItems;
    public int mode = MODE_NONE;// 当前操作模式

    public ImageViewTouch mImgView;
    public CropImageView mCropView;
    public RotateImageView mRotateImageView;

    private BeautyFragment mBeautyFragment;
    private FilterFragment mFilterFragment;
    private CropFragment mCropFragment;
    private RotateFragment mRotateFragment;
    private ColorTuneFragment mColorTuneFragment;

    private Dialog myRepairDialog;
    private StkLinearLayout llRepair;
    private TextView tvRepairNum, tvRepairSuc;


    @Override
    protected int onCreate() {
        return R.layout.activity_pic_edit;
    }

    @Override
    public void onBackPressed() {
        switch (mode) {
            case MODE_BEAUTY:
                mBeautyFragment.backToMain();
                return;
            case MODE_FILTER:
                mFilterFragment.backToMain();
                return;
            case MODE_CROP:
                mCropFragment.backToMain();
                return;
            case MODE_ROTATE:
                mRotateFragment.backToMain();
                return;
            case MODE_COLOR_TUNE:
                mColorTuneFragment.backToMain();
                return;
            default:
                break;
        }
        super.onBackPressed();
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivPicEditBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivPicEditSave.setOnClickListener(this);
        mDataBinding.tvPicBeauty.setOnClickListener(this);
        mDataBinding.tvPicFilter.setOnClickListener(this);
        mDataBinding.tvPicCut.setOnClickListener(this);
        mDataBinding.tvPicRotate.setOnClickListener(this);
        mDataBinding.tvPicAdjust.setOnClickListener(this);
        mDataBinding.tvPicRepair.setOnClickListener(this);

        mImgView = mDataBinding.imageViewTouch;
        mCropView = mDataBinding.cropImgView;
        mRotateImageView = mDataBinding.myRotateView;
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvPicBeauty://美颜
                showFragmentByFunc(mFuncItems.get(0));
                break;
            case R.id.tvPicFilter://滤镜
                showFragmentByFunc(mFuncItems.get(1));
                break;
            case R.id.tvPicCut://裁剪
                showFragmentByFunc(mFuncItems.get(2));
                break;
            case R.id.tvPicRotate://旋转
                showFragmentByFunc(mFuncItems.get(3));
                break;
            case R.id.tvPicAdjust://色调
                showFragmentByFunc(mFuncItems.get(4));
                break;
            case R.id.tvPicRepair://照片修复
                repair();
                break;
            case R.id.ivPicEditSave://保存
                saveImg();
                break;

        }
    }

    @Override
    protected void initData() {
        mRetBitmap = ImageUtils.getBitmap(sImgPath);
        mFuncItems = getFuncData();
        mDataBinding.imageViewTouch.setImageBitmap(mRetBitmap);
        mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
    }

    //保存图片
    private void saveImg() {
        showDialog(getString(R.string.saving));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        ImageUtils.save2Album(mRetBitmap, Bitmap.CompressFormat.PNG);
                        //保存到历史作品
                        String filePath = FileUtil.generateFilePath(Content.myEditWork, ".png");
                        ImageUtils.save(mRetBitmap, filePath, Bitmap.CompressFormat.PNG);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.save_success));
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    private List<FuncBean> getFuncData() {
        if (mFuncItems != null) {
            return mFuncItems;
        }
        List<FuncBean> funcBeans = new ArrayList<>();
        mFuncItems = funcBeans;
        FuncBean funcBean = null;
        funcBean = new FuncBean(FuncBean.FUNC_BEUITY, getString(R.string.pic_beauty), R.drawable.my);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_FILTER, getString(R.string.pic_filter), R.drawable.lj);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_CROP, getString(R.string.pic_cut), R.drawable.caijian);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_ROTATION, getString(R.string.pic_rotate), R.drawable.xuanzhuan);
        funcBeans.add(funcBean);
        funcBean = new FuncBean(FuncBean.FUNC_COLOR_TUNE, getString(R.string.pic_adjust), R.drawable.sediao);
        funcBeans.add(funcBean);


        return funcBeans;
    }

    private void showFragmentByFunc(FuncBean funcBean) {
        if (funcBean == null) {
            return;
        }

        showEdit(funcBean.getName());
        switch (funcBean.getFunc()) {
            case BeautyFragment.INDEX:
                showBeautyFragment();
                break;
            case FilterFragment.INDEX:
                showFilterFragment();
                break;
            case CropFragment.INDEX:
                showCropFragment();
                break;
            case RotateFragment.INDEX:
                showRotateFragment();
                break;
            case ColorTuneFragment.INDEX:
                showColorTuneFragment();
                break;
            default:
                break;
        }
    }

    private void showBeautyFragment() {
        if (mBeautyFragment == null) {
            mBeautyFragment = BeautyFragment.newInstance();
        } else {
            mBeautyFragment.onShow();
        }
        showFragment(mBeautyFragment);
    }

    private void showFilterFragment() {
        if (mFilterFragment == null) {
            mFilterFragment = FilterFragment.newInstance();
        } else {
            mFilterFragment.onShow();
        }
        showFragment(mFilterFragment);
    }

    private void showCropFragment() {
        if (mCropFragment == null) {
            mCropFragment = CropFragment.newInstance();
        } else {
            mCropFragment.onShow();
        }
        showFragment(mCropFragment);
    }

    private void showRotateFragment() {
        if (mRotateFragment == null) {
            mRotateFragment = RotateFragment.newInstance();
        } else {
            mRotateFragment.onShow();
        }
        showFragment(mRotateFragment);
    }

    private void showColorTuneFragment() {
        if (mColorTuneFragment == null) {
            mColorTuneFragment = ColorTuneFragment.newInstance();
        } else {
            mColorTuneFragment.onShow();
        }
        showFragment(mColorTuneFragment);
    }

    private void showFragment(BaseEditFragment baseEditFragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.flFragmentContainer, baseEditFragment);
        fragmentTransaction.commit();
    }

    public Bitmap getMainBit() {
        return mRetBitmap;
    }

    public void changeMainBitmap(Bitmap newBit, boolean needPushUndoStack) {
        if (newBit == null) {
            return;
        }

        if (mRetBitmap != newBit) {
            mRetBitmap = newBit;
            mImgView.setImageBitmap(mRetBitmap);
            mImgView.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        }
    }

    private void showEdit(String name) {
        mDataBinding.tvPicEditTitle.setText(name);
        mDataBinding.llPicEditBottom.setVisibility(View.GONE);
        mDataBinding.flFragmentContainer.setVisibility(View.VISIBLE);
    }

    public void showFunc() {
        mDataBinding.tvPicEditTitle.setText(getString(R.string.pic_edit));
        mDataBinding.llPicEditBottom.setVisibility(View.VISIBLE);
        mDataBinding.flFragmentContainer.setVisibility(View.INVISIBLE);
    }

    private void repair() {
        //照片修复弹框
        repairDialog();
        myRepairDialog.show();
        Random random = new Random();
        tvRepairNum.setText(random.nextInt(80) + getString(R.string.percent));
        ApiManager.visionAiApi().repairOldPhoto(this, mRetBitmap, new IReqRetCallback<Bitmap>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable Bitmap result) {
                if (result != null) {
                    mRetBitmap = result;
                    tvRepairSuc.setText(100 + getString(R.string.percent));
                    mDataBinding.imageViewTouch.setImageBitmap(result);
                }
                myRepairDialog.dismiss();
                ToastUtils.showShort(msg);
            }
        });
    }

    //照片修复弹框
    private void repairDialog() {
        myRepairDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_pic_repair, null);
        myRepairDialog.setContentView(inflate);
        myRepairDialog.setCancelable(true);
        myRepairDialog.setCanceledOnTouchOutside(false);
        Window dialogWindow = myRepairDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        llRepair = inflate.findViewById(R.id.llRepairing);
        tvRepairNum = inflate.findViewById(R.id.tvRepairNum);
        tvRepairSuc = inflate.findViewById(R.id.tvRepairSuc);
    }

}